#!/usr/bin/perl -w

###############################################################################
# Transform the idlink input files into a database load file.
#
# Parameters needed: idlink_files, pheno_files, temp_dir
# Output file: temp_dir/idlink.out
#
# Author: Herodotos Herodotou and Nedyalko Borisov
# Date: March 11, 2010
#
##############################################################################

use getOpts qw(get_options println);
sub create_exp_to_sample_map;

if ($#ARGV != 0)
{
   println qq(Please specify the .properties file);
   println qq(Usage: perl $0 load.properties);
   exit(-1);
}

# Get input parameters
%opt = get_options($ARGV[0]);
$ID_LINK_FILES = $opt{'idlink_files'};
$PHENO_FILES = $opt{'pheno_files'};
$TEMP_DIR = $opt{'temp_dir'};

# Open output file
open OUTFILE, ">", $TEMP_DIR."/idlink.out" or die $!;


# Perform the transformation
@idlinkfiles = split(/;/, $ID_LINK_FILES);
$got_sample_from_pheno = 0;

foreach (@idlinkfiles)
{
    $idlinkfile = $_;
    $idlinkfile =~ s/\s+$//;
    $num_records = 0;
    
    # Open files
    println qq(Transform idlink file: $idlinkfile);
    open INFILE, "<", $idlinkfile or die $!;

    # Get the header and check if it contains a sampleid column
    $header = <INFILE>;
    my %exp_to_sample = ();
    if ($header !~ /sampleid/i && $got_sample_from_pheno == 0)
    {
       # In affy, the sampleid is in the pheno files - get it
       %exp_to_sample = create_exp_to_sample_map();
       $got_sample_from_pheno = 1;
    }
    
    # Generate the out file
    while($line = <INFILE>)
    {
       $line =~ s/\s+$//;
       @data = split(/,/, $line);
       $num_cols = @data;
       
       if ($num_cols < 5)
       {
          if (exists $exp_to_sample{$data[1]})
          {
             print OUTFILE qq($data[1],$data[2],$data[3],$exp_to_sample{$data[1]}\n);
          }
          else
          {
             print OUTFILE qq($data[1],$data[2],$data[3],NULL\n);
          }
       }
       else
       {
          print OUTFILE qq($data[1],$data[2],$data[3],$data[4]\n);
       }
       ++$num_records;
    }

    # Close file
    close INFILE;
    println qq(Done idlink file transformation - produced $num_records records);
}

# Done
close OUTFILE;


###############################################################################
# Function: create_ref_exp_to_sample
#
# Input: none
#
# Description: This function creates a returns a mapping key->value,
#              where the key is the exp_id and the value is the sampleid.
#
##############################################################################
sub create_exp_to_sample_map()
{
    my @phenofiles = split(/;/, $PHENO_FILES);
    my %exp_to_sample = ();

    foreach (@phenofiles)
    {
        # Open file
        my $phenofile = $_;
        $phenofile =~ s/\s+$//;
        open PHENOFILE, "<", $phenofile or die $!;

        # Get the header line
        my $header = <PHENOFILE>;
        my @headers = split(/,/, $header);
        
        # Find the location of the sampleid column
        my $num_headers = @headers;
        my $sample_location = -1;
        for ($i = 0; $i < $num_headers; $i++)
        {
           if ($headers[$i] =~ m/sampleid/i)
           {
              $sample_location = $i;
              last;
           }
        }
        
        # Check if we found a sample column
        if ($sample_location == -1)
        {
           next;
        }
        
        while(my $line = <PHENOFILE>)
        {
            # Read the mapping
           $line =~ s/\s+$//;
           my @data = split(/,/, $line);
           $exp_to_sample{$data[1]} = $data[$sample_location];
        }

        # Close file
        close PHENOFILE;
    }

   return %exp_to_sample;
}

